package com.wsd.jing.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsd.jing.entity.Department;
import com.wsd.jing.entity.User;
import com.wsd.jing.mapper.DepartmentMapper;
import com.wsd.jing.mapper.UserMapper;
import com.wsd.jing.vo.DepartmentVO;
import com.wsd.jing.constant.SystemConstant;
import com.wsd.jing.enums.CodeEnum;
import com.wsd.jing.exception.BusinessException;
import com.wsd.jing.request.CommonRequest;
import com.wsd.jing.service.IDepartmentService;
import com.wsd.jing.utils.SortUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * All rights Reserved, Designed By www.tom.com
 *
 * @author tom
 * @version 1.0.0
 * @projectName: jing
 * @packageName: com.wsd.jing.service.impl
 * @className: DepartmentServiceImpl
 * @description: 部门服务实现类
 * @createDate 2022-11-20 07:41
 * @copyright 2022-11-20 07:41 www.tom.com Inc. All rights reserved.
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    private final UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertDepartment(Department department) {
        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.lambda().eq(Department::getParentId, department.getParentId()).eq(Department::getName, department.getName());
        Department department1 = this.getOne(departmentQueryWrapper);
        if (ObjectUtil.isNotNull(department1)) {
            throw new BusinessException(CodeEnum.DEPARTMENT_NAME_EXIST);
        }
        department.setCreateTime(LocalDateTime.now());
        return this.save(department);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateDepartment(Department department) {
        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.lambda().eq(Department::getParentId, department.getParentId()).eq(Department::getName, department.getName());
        Department department1 = this.getOne(departmentQueryWrapper);
        if (ObjectUtil.isNotNull(department1) && !department.getId().equals(department1.getId())) {
            throw new BusinessException(CodeEnum.DEPARTMENT_NAME_EXIST);
        }
        department.setUpdateTime(LocalDateTime.now());
        return this.updateById(department);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteDepartment(Integer id) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(User::getDepartmentId, id);
        List<User> userList = userMapper.selectList(userQueryWrapper);
        if (CollectionUtil.isNotEmpty(userList)) {
            throw new BusinessException(CodeEnum.DEPARTMENT_NOT_DELETE);
        }
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteDepartments(String ids) {
        List<String> idList = StrUtil.splitTrim(ids, ",");
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().in(User::getDepartmentId, idList);
        List<User> userList = userMapper.selectList(userQueryWrapper);
        if (CollectionUtil.isNotEmpty(userList)) {
            throw new BusinessException(CodeEnum.DEPARTMENT_NOT_DELETE);
        }
        return this.removeByIds(idList);
    }

    @Override
    public Department getDepartment(Integer id) {
        return this.getById(id);
    }

    @Override
    public List<Department> listDepartments(CommonRequest commonRequest, Department department) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        // TODO 设置查询条件

        // 处理排序字段
        SortUtil.handleListSort(commonRequest, queryWrapper);
        return this.list(queryWrapper);
    }

    @Override
    public Map<String, Object> listPageDepartments(CommonRequest commonRequest, Department department) {
        Map<String, Object> resultMap = new HashMap<>(2);
        Page<Department> page = new Page<>(commonRequest.getPageNum(), commonRequest.getPageSize());
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        // TODO 设置查询条件
        if (StrUtil.isNotBlank(department.getName())) {
            queryWrapper.lambda().like(Department::getName, department.getName());
        }
        if (department.getParentId() != null) {
            queryWrapper.lambda().eq(Department::getParentId, department.getParentId());
        }

        // 处理排序字段
        SortUtil.handlePageSort(commonRequest, page);
        IPage<Department> result = this.page(page, queryWrapper);
        resultMap.put("rows", result.getRecords());
        resultMap.put("total", result.getTotal());
        return resultMap;
    }

    @Override
    public List<DepartmentVO> listTreeDepartments() {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Department::getStatus, 1).orderByAsc(Department::getSort);
        List<Department> departmentList = this.list(queryWrapper);
        return convertTree(departmentList, SystemConstant.DEPARTMENT_PARENT_ID);
    }

    /**
     * @param id :
     * @return List<Integer>
     * @author tom
     * @description 查询本部门及下级部门ID
     * @createDate 2024/6/13 17:43
     */
    @Override
    public Set<String> listTreeDepartmentIds(Integer id) {
        List<Department> departmentList = this.list();
        Set<String> departmentIdSet = getDepartmentIdSet(departmentList, id);
        departmentIdSet.add(String.valueOf(id));
        return departmentIdSet;
    }

    /**
     * @param departmentList:
     * @param pid:
     * @return List<DepartmentVO>
     * @author tom
     * @description 部门转树结构
     * @createDate 2022/11/23 18:45
     */
    private List<DepartmentVO> convertTree(List<Department> departmentList, Integer pid) {
        List<DepartmentVO> result = new ArrayList<>();
        for (Department department : departmentList) {
            DepartmentVO departmentVo = new DepartmentVO();
            departmentVo.setId(department.getId());
            departmentVo.setName(department.getName());
            Integer departmentId = department.getId();
            Integer parentId = department.getParentId();
            if (parentId != null) {
                if (parentId.equals(pid)) {
                    //递归查询当子部门
                    List<DepartmentVO> departmentVoList = convertTree(departmentList, departmentId);
                    departmentVo.setChildren(departmentVoList);
                    result.add(departmentVo);
                }
            }
        }
        return result;
    }

    /**
     * @param departmentList:
     * @param pid:
     * @return Set<String>
     * @author tom
     * @description 查询当前部门的所有下级部门
     * @createDate 2024/6/14 17:10
     */
    private Set<String> getDepartmentIdSet(List<Department> departmentList, Integer pid) {
        Set<String> resultSet = new HashSet<>();
        for (Department department : departmentList) {
            Integer departmentId = department.getId();
            Integer parentId = department.getParentId();
            if (parentId != null) {
                if (parentId.equals(pid)) {
                    //递归查询当子部门
                    getDepartmentIdSet(departmentList, departmentId);
                    resultSet.add(departmentId.toString());
                }
            }
        }
        return resultSet;
    }
}
